﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<OurSite.WebAdmin.Models.EventModel>" %>
<%@ Import Namespace="OurSite.Business.Category"%>
<%@ Import Namespace="OurSite.Business.Event"%>
<%@ Import Namespace="OurSite.Business.Picture"%>
<%@ Import Namespace="OurSite.WebAdmin.HTMLHelpers"%>


<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	Edit Event
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="HeaderContent" runat="server">
   
    <script type="text/javascript">
        var blankGuid = "00000000-0000-0000-0000-000000000000";
        var pictureId = "";
        var code = "";
        $(document).ready(function()
        {
            $("#pictureTable").tableDnD();

            // Initialise the second table specifying a dragClass and an onDrop function that will display an alert
            $("#pictureTable").tableDnD({
                onDragClass: "myDragClass",
                onDrop: function(table, row)
                {
                    var rows = table.tBodies[0].rows;
                    for (var i = 0; i < rows.length; i++)
                    {
                        if (rows[i].id != "") //header needs to be excluded
                            $("#" + rows[i].id + " input[id*=order_]").val(i);
                    }
                },
                onDragStart: function(table, row)
                {
                }
            });


            $("#subCategoryCreate").dialog({ autoOpen: false, modal: true, buttons: { "Save": subCategoryCreateSave, "Cancel": subCategoryCreateClose }, overlay: { opacity: 0.5, background: "black" }, resizable: false, title: "Create a new sub category" });
            $("#categoryCreate").dialog({ autoOpen: false, modal: true, buttons: { "Save": categoryCreateSave, "Cancel": categoryCreateClose }, overlay: { opacity: 0.5, background: "black" }, resizable: false, title: "Create a new parent category" });
            $("#addEventCategory").dialog({ autoOpen: false, modal: true, buttons: { "Add": eventcategorySave, "Cancel": eventCategoryAddClose }, overlay: { opacity: 0.5, background: "black" }, width: 500, resizable: false, title: "Add category to event" });
            $("#pictureDetail").dialog({ autoOpen: false, modal: true, buttons: { "Save": pictureDetailSave, "Cancel": pictureDetailClose }, overlay: { opacity: 0.5, background: "black" }, width: 800, resizable: false, title: "Picture detail" });
            $("#peopleEdit").dialog({ autoOpen: false, modal: true, buttons: { "Save": peopleEditSave, "Cancel": peopleEditClose }, overlay: { opacity: 0.5, background: "black" }, width: 500, resizable: false, title: "People edit" });

            $("#Region").autocomplete({
                source: function(request, response)
                {
                    $.ajax({
                        url: '<%=Url.Action("RegionLookup", "Event") %>',
                        data: ({ lookupValue: request.term }),
                        success: function(data) { response(data) }
                    });
                },
                minLength: 1
            });

            $("#Country").autocomplete({
                source: function(request, response)
                {
                    $.ajax({
                        url: '<%=Url.Action("CountryLookup", "Event") %>',
                        data: ({ region: $("#Region").val(), lookupValue: request.term }),
                        success: function(data) { response(data) }
                    });
                },
                minLength: 1
            });

            $("#State").autocomplete({
                source: function(request, response)
                {
                    $.ajax({
                        url: '<%=Url.Action("StateLookup", "Event") %>',
                        data: ({ country: $("#Country").val(), lookupValue: request.term }),
                        success: function(data) { response(data) }
                    });
                },
                minLength: 1
            });

            $("#City").autocomplete({
                source: function(request, response)
                {
                    $.ajax({
                        url: '<%=Url.Action("CityLookup", "Event") %>',
                        data: ({ state: $("#State").val(), lookupValue: request.term }),
                        success: function(data) { response(data) }
                    });
                },
                minLength: 1
            });

            $("input[id*=delete_]").change
            (
                function()
                {
                    if ($(this).attr("checked") && $("input[id*='islisting'][value='" + $(this).attr("value") + "']").is(":checked"))
                    {
                        $(this).attr("checked", "");
                        alert(" This image is set as the listing image, so you have to set another image to the listing image before deleting this image.");
                    }
                }
            );

            $("#StartDate").datepicker();
            $("#EndDate").datepicker();

            $("#parentCategories").removeAttr("multiple");
            $("#parentCategories").change
            (
                function()
                {
                    $.ajax({
                        url: '<%=Url.Action("GetSubCategories", "Event") %>',
                        data: "parentId=" + $(this).val(),
                        success: function(data)
                        {
                            $("#subCategories").html(data);
                            $("#lnksubCategoryCreate").show();
                        }
                    });
                }
            );

            if ($("#ParentId").val() != blankGuid)
            {
                $("#parentEvents").val($("#ParentId").val());
            }

            $("#parentEvents").change
            (
                function() { $("#ParentId").val($(this).val()); }
            );

            $("#FileUpload").uploadify({
                uploader: "/Content/uploadify.swf",
                cancelImg: "/Content/images/cancel.png",
                buttonText: "Upload Images",
                script: '<%=Url.Action("UploadPicture", "Event") %>',
                folder: "uploads",
                fileDesc: "Image Files",
                fileExt: "*.jpg;*.jpeg",
                multi: true,
                auto: true,
                fileDataName: 'fileData',
                scriptData: { 'EventID': $("#EventId").val() },

                onAllComplete: function(event, data)
                {
                    window.location = window.location;
                }
            });

            if ($("#EventId").val() == blankGuid)
            {
                $("#categorySection").hide();
                $("#pictureSection").hide();
            }
            else
            {
                $("#categorySection").show();
                $("#pictureSection").show();
            }

        });
        
        
// ------ FUNCTIONS -------- //
        function categoryCreateOpen() { $("#categoryCreate").dialog("open"); }
        function categoryCreateClose() { $("#categoryCreate").dialog("close"); }
        function categoryCreateSave()
        {
            var newCategory = $("#txtCategory").val();
            $.ajax({
                url: '<%=Url.Action("SaveCategory", "Event") %>',
                data: ({ categoryName: newCategory }),
                success: function(data)
                {
                    $("#parentCategories").html(data);
                    $("#subCategories").html("");
                    $("#txtCategory").val("");
                    categoryCreateClose();
                }
            });
        }

        function subCategoryCreateOpen() { $("#subCategoryCreate").dialog("open"); }
        function subCategoryCreateClose() { $("#subCategoryCreate").dialog("close"); }
        function subCategoryCreateSave()
        {
            var partentId = $("#parentCategories").val();
            var newsubCategory = $("#txtsubCategory").val();
            $.ajax({
                url: '<%=Url.Action("SaveSubCategory", "Event") %>',
                data: ({parentId : partentId, categoryName: newsubCategory}),
                success: function(data)
                {
                    $("#subCategories").html(data);
                    $("#txtsubCategory").val("");
                    subCategoryCreateClose();
                }
            });
        }

        function eventCategoryAddOpen() { $("#addEventCategory").dialog("open"); }
        function eventCategoryAddClose() { $("#addEventCategory").dialog("close"); }
        function eventcategorySave()
        {
            var categoryId = $("#subCategories").val();
            var eventId = $("#EventId").val();
            $.ajax({
                url: '<%=Url.Action("SaveEventCategory", "Event") %>',
                data: ({ eventId: eventId, categoryId: categoryId }),
                success: function(data)
                {
                    eventCategoryAddClose();
                    $("#tbleventCategory").html("<tr><th colspan='4'>Current Event Categories</th></tr>" + data);
                }
            });
        }
        function deleteEventCategory(categoryId)
        {
            var eventId = $("#EventId").val();
            $.ajax({
                url: '<%=Url.Action("DeleteEventCatgory", "Event") %>',
                data: ({ eventId: eventId, categoryId: categoryId }),
                success: function(data)
                {

                    $("#tbleventCategory").html("<tr><th colspan='4'>Current Event Categories</th></tr>" + data);
                }
            });
        }

        function pictureDetailOpen(obj)
        {
            pictureId = $(obj).attr("pictureID");
            code = $(obj).attr("pictureCode");
            var src = $(obj).attr("src");
            var caption = $("#caption_" + code).val();

            SetPeopleCheckBox(pictureId);

            $("#pictureDetailImage").attr("src", src);
            $("#pictureDetailCaption").val(caption);
            $("#pictureDetail").dialog("open"); 
        }
        function pictureDetailClose() { $("#pictureDetail").dialog("close"); }
        function pictureDetailSave()
        {
            var caption = $("#pictureDetailCaption").val();
            var peopleIds = "";
            var pictureOrder = $("input[id='order_" + code + "']").val();

            $("input[id='people']:checked").each
            (
                function()
                {
                    if (peopleIds != "")
                        peopleIds += ",";
                        
                    peopleIds += $(this).val();
                }
            );

                $.ajax({
                    url: '<%=Url.Action("SavePicture", "Event") %>',
                    type: "POST",
                    data: ({ pictureId: pictureId, caption: caption, people: peopleIds, order: pictureOrder }),
                    success: function(data)
                    {
                        $("#caption_" + code).val(caption);
                        pictureDetailClose();
                    }
                });
        }

        function peopleEditOpen(id, first, last, maiden, isHuman, birthDate)
        {
            $("#txtPeopleId").val(id);
            $("#txtPeopleFirst").val(first);
            $("#txtPeopleLast").val(last);
            $("#txtPeopleMaiden").val(maiden);
            $("#chkIsHuman").attr("checked", isHuman);
            $("#txtBirthDate").val(birthDate);
            
            $("#peopleEdit").dialog("open");
        }
        function peopleEditClose() { $("#peopleEdit").dialog("close"); }
        function peopleEditSave()
        {
            var id = $("#txtPeopleId").val();
            if (id == "")
                id = blankGuid;
  
            var firstName = $("#txtPeopleFirst").val();
            var lastName = $("#txtPeopleLast").val();
            var maidenName = $("#txtPeopleMaiden").val();
            var isHuman = $("#chkIsHuman").is(':checked');
            var birthDate = $("#txtBirthDate").val();
            $.ajax({
                url: '<%=Url.Action("SavePeople", "Event") %>',
                data: ({ PeopleId: id, FirstName: firstName, LastName: lastName, MaidenName: maidenName, isHuman: isHuman, birthDate: birthDate }),
                success: function(data)
                {
                    $("#pictureDetailPeopleContent").html(data);
                    SetPeopleCheckBox(pictureId);
                    peopleEditClose();
                }
            });
        }

        function SetPeopleCheckBox(id)
        {
            // reset all the checkboxes
            $("input[id='people']:checked").attr("checked", "");
            
            $.ajax({
                url: '<%=Url.Action("GetPicturePeople", "Event") %>',
                data: ({ pictureId: id }),
                success: function(data)
                {
                    $.each
                    (data,
                        function(index, value)
                        {
                            $("input[value=" + value.PeopleId + "]").attr("checked", "checked");
                        }
                    );
                }
            });
        }


	</script>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%= Html.ActionLink("Create new Event", "EditEvent", "Event", new {id = 0})%>
    <h2>Edit Event</h2>
    <div class="validation-summary-errors"><%= Html.Encode(ViewData["EventSaveMessage"])%></div>
    <% using (Html.BeginForm()) { %>
        <div>
            <fieldset>
                <legend>Event Information</legend>
                <%= Html.TextBoxFor(m => m.EventId, new { style="display:none;"})%>
                <%= Html.TextBoxFor(m => m.EventCode, new { style = "display:none;" })%>
                <%= Html.TextBoxFor(m => m.ParentId, new { style = "display:none;" })%>
                
                <%if (Model.ListingPicture != null)
                  {%>
                    <img class="floatLeft paddingRight20" src="<%= ConfigurationManager.AppSettings["ImagePrefix"] + Model.ListingPicture.ImagePath%>" />
                <%} %>
                <div class="floatLeft paddingRight20">
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.EventName)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.EventName)%><br />
                        <%= Html.ValidationMessageFor(m => m.EventName)%>
                    </div>
                    
                    <div class="editor-label">
                        Parent Event
                    </div>
                    <div class="editor-field">
                        <select id="parentEvents">
                            <%= "<option value=''>- Select One -</option>"%>
                        <% foreach (Event e in Model.ParentEvents) { %>
                            <%= "<option value='" + e.Id + "'>" + e.Name + "</option>"%>       
                        <%} %>
                        </select>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.StartDate)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.StartDate)%><br />
                        <%= Html.ValidationMessageFor(m => m.StartDate)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.EndDate)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.EndDate)%><br />
                        <%= Html.ValidationMessageFor(m => m.EndDate)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.ShortDescription)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextAreaFor(m => m.ShortDescription)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.LongDescription)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextAreaFor(m => m.LongDescription)%>
                    </div>
                </div>
                
                <div class="floatLeft">
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.Region) %>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.Region)%>
                    </div>
                     
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.Country)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.Country)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.Label("State/Province")%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.State)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.City)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.City)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.Location)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.Location)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.Order)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.Order)%>
                    </div>
                    
                    <div class="editor-label">
                        <%= Html.LabelFor(m => m.AlternateURL)%>
                    </div>
                    <div class="editor-field">
                        <%= Html.TextBoxFor(m => m.AlternateURL)%>
                    </div>
                </div>
                
            </fieldset>
        </div>
        
        <div id="categorySection">
            <fieldset>
                <legend>Category Information</legend>
                
                <table id="tbleventCategory">
                    <tr><th colspan='4'>Current Event Categories</th></tr>   
         
                    <%= HTMLHelper.EventCategoryTable(Model.EventCategories) %>
                    
                </table>
                <br />
                <input id="btnCategoryAdd" type="button" onclick="eventCategoryAddOpen();" value="Add Category to event" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"/>
                
            </fieldset>
        </div>
        <div id="debugArea"></div>
        <div  id="pictureSection">
            <fieldset>
                <legend>Pictures</legend>
                    <table id="pictureTable">
                        <tr  class="nodrop">
                            <th>Order</th>
                            <th>Picture</th>
                            <th>Caption</th>
                            <th>Event Listing</th>
                            <th>Is Favorite</th>
                            <th>Upload to Facebook</th>
                            <th>Delete Image?</th>
                            
                        </tr>
                        
                        <% foreach (Picture p in Model.Pictures)
                           { %>
                            <tr id="<%=p.Order %>">
                                <td><%= Html.TextBox("order_" + p.PictureCode, p.Order ) %></td>
                                <td>
                                    <img src="<%= ConfigurationManager.AppSettings["ImagePrefix"] + p.ImagePath %>" height="150" onclick="pictureDetailOpen(this);" pictureCode='<%=p.PictureCode %>' pictureID='<%=p.Id %>'/>
                                </td>
                                <td>
                                    <%= Html.TextBox("caption_" + p.PictureCode, p.Caption) %>
                                </td>
                                <td><%= Html.RadioButton("islisting", p.PictureCode.ToString(), p.IsListing)%></td>
                                <td><%= Html.CheckBox("isFavorite_" + p.PictureCode, p.IsFavorite ) %></td>
                                <td><%= Html.CheckBox("isfacebook_" + p.PictureCode, string.IsNullOrEmpty(p.FacebookId) ? false : true)%></td>
                                <td><%= Html.CheckBox("delete_" + p.PictureCode, new {value=p.PictureCode} ) %></td>
                            </tr>    
                        <%}%>
                        
                    </table>
                    <input type="file" id="FileUpload" name="FileUpload" />
            </fieldset>
        </div>
        
        <p class="clearBoth">
            <input type="submit" value="Save" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />
        </p>
        
        <div id="categoryCreate">
            Category Name: <input id="txtCategory" />
        </div>
        
        <div id="subCategoryCreate">
            Sub Category Name: <input id="txtsubCategory" />
        </div>
        
        <div id="addEventCategory">
            <table>
                    <tr>
                        <td>
                            <%= Html.ListBox("parentCategories", new SelectList(Model.ParentCategories, "Id", "Name"), new { multiple = "", size="6" })%>
                        </td>
                        <td>
                            <select id="subCategories" size="6"></select>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <a onclick="categoryCreateOpen();"  class="cursor">Create new Parent Category</a>
                        </td>
                        <td>
                            <a id="lnksubCategoryCreate" onclick="subCategoryCreateOpen();" class="displayNone cursor">Create new Sub Category</a>
                        </td>
                    </tr>
                </table>
        </div>
        
        <div id="pictureDetail">
            <div class="floatLeft paddingRight20">
                <img src="/Content/images/cancel.png" id="pictureDetailImage" />
                <div class="editor-label">Caption: </div>
                <div class="editor-field">
                    <input type="text" id="pictureDetailCaption" />
                </div>
            </div>
            <div id="pictureDetailPeople">
                <fieldset>
                <legend>Tag People to picture</legend>
                <div id="pictureDetailPeopleContent" style="overflow:scroll; height:350px">
                    <%= HTMLHelper.PeopleCheckList(Model.People) %>
                </div>
                
                <input id="btnAddPeople" type="button" onclick="peopleEditOpen('', '','','');" value="Add new person" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"/>
                
                </fieldset>
            </div>
        </div>
        
        <div id="peopleEdit">
            <input id="txtPeopleId" class="displayNone" />
            <table>
                <tr>
                    <td>First Name:</td>
                    <td><input id="txtPeopleFirst" type="text"/></td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input id="txtPeopleLast" type="text" /></td>
                </tr>
                <tr>
                    <td>Maiden Name:</td>
                    <td><input id="txtPeopleMaiden" type="text" /></td>
                </tr>
                <tr>
                    <td>Is Human:</td>
                    <td><input id="chkIsHuman" type="checkbox" /></td>
                </tr>
                <tr>
                    <td>Birth Date:</td>
                    <td><input id="txtBirthDate" type="text" /></td>
                </tr>
            </table>
        </div>
    <% } %>
    

</asp:Content>

